<template>
  <ElContainer :class="s.evaluation">
    <ElButton
      v-if="activeTab === '1'"
      type="warning"
      round
      class="btn-back"
      @click="back(true)"
    >
      <i class="icon-undo2"></i>
      返回主页</ElButton
    >
    <ElTabs
      v-model="activeTab"
      class="tab-step"
      type="card"
      tab-position="bottom"
      @tab-click="next"
    >
      <ElTabPane label="评测" class="tab-pane">
        <template>
          <BabySearch
            :key="babySearchId"
            v-model="childInfo"
            :baby-id="`${activeName.params.babyId || backBabyId || 0}`"
            @upInfo="upInfo"
          />
          <ElCard class="baby">
            <div class="one">
              <div class="child">
                <span class="item-icon"></span
                ><span class="item-text">体格评测</span>
              </div>
              <div class="child">
                <span class="must-check no-content">* </span>身高：
                <ElInput
                  v-model="height"
                  class="float-right w120"
                  placeholder=""
                  type="number"
                  @change="changeEditStatus"
                  @keyup.enter.native="nextToWeight"
                ></ElInput>
                cm
              </div>
              <div class="child">
                <span class="must-check no-content">* </span>体重：
                <ElInput
                  ref="weight"
                  v-model="weight"
                  class="float-right w120"
                  placeholder=""
                  type="number"
                  @change="changeEditStatus"
                  @keyup.enter.native="upInfo"
                ></ElInput>
                kg
              </div>
              <div class="child"></div>
            </div>
          </ElCard>
          <section class="questions">
            <ElCard class="baby">
              <div class="one with-tips">
                <div class="child">
                  <span class="item-icon"></span
                  ><span class="item-text">体质评测</span>
                </div>
                <div class="tips">依据宝宝近三个月的情况回答如下问题</div>
              </div>
            </ElCard>
            <TiZhiQuestions :key="questionId" v-model="answers" />
          </section>
          <div class="submit" @click="upInfo">提交</div>
        </template>
      </ElTabPane>
      <ElTabPane label="下一步2">
        <EvaluationResult :id="`${id}`" @back="back(true)" />
      </ElTabPane>
    </ElTabs>
  </ElContainer>
</template>

<script>
import _ from 'lodash';
import {http, catchAppError} from '@/util';
import {menusNavigation} from '@/store';
import url from '@/config';
import TiZhiQuestions from '@/components/evaluation/TiZhiQuestions.vue';
import EvaluationResult from '@/components/evaluation/EvaluationResult.vue';
import BabySearch from '@/components/evaluation/BabySearch.vue';
import toast from '@/toast';
import changeEditStatus from '@/components/evaluation/EvalutionEditStatus';

export default {
  name: 'Evaluation',
  components: {TiZhiQuestions, EvaluationResult, BabySearch},
  props: {
    activeName: {
      type: Object,
      default: () => ({
        nav: '0',
        params: {}
      })
    }
  },
  data() {
    return {
      babySearchId: 0,
      questionId: 0,
      activeTab: '0',
      id: '',
      child: null,
      height: '',
      weight: '',
      children: [],
      childRequest: null,
      requestArray: [],
      childInfo: {},
      answers: null,
      isNewBaby: false,
      backBabyId: '0',
      pickOptions: {
        disabledDate(time) {
          return (
            time.getTime() > Date.now() ||
            time.getTime() < Date.now() - 1000 * 60 * 60 * 24 * 365 * 18
          );
        }
      }
    };
  },
  watch: {
    answers() {
      if (this.answers) {
        changeEditStatus();
      }
    }
  },
  beforeMount() {
    http
      .post(url.testChildList)
      .then(res => {
        this.children = res;
      })
      .catch(catchAppError);
  },
  methods: {
    changeEditStatus,
    clearData() {
      this.height = '';
      this.weight = '';
      this.requestArray = [];
      this.answers = null;
      this.questionId = _.uniqueId();
    },
    clearBabyInfo() {
      this.id = '';
      this.child = null;
      this.childInfo = {isClear: true};
      this.babySearchId = _.uniqueId();
    },
    nextToWeight() {
      this.$refs.weight.focus();
    },
    upInfo() {
      if (!this.childInfo.id) {
        const childIsAllCheck =
          this.childInfo.child_name &&
          this.childInfo.birthday &&
          this.childInfo.sex;
        if (childIsAllCheck) {
          this.childRequest = true;
          // this.childRequest = this.upData(url.addMember, childParams);
        } else {
          if (!this.childInfo.child_name) {
            toast('请填写宝宝姓名');
            return;
          }
          if (!this.childInfo.birthday) {
            toast('请填写宝宝生日');
            return;
          }
          if (!this.childInfo.sex) {
            toast('请选择宝宝性别');
            return;
          }
        }
      }
      let physiqueParams = null;
      let physicalParams = null;
      if (+this.height < 0 || +this.weight < 0) {
        toast('体格信息只能填写数字');
        return;
      }
      const questionPhysiqueNotComplete =
        (!+this.height && +this.weight) || (+this.height && !+this.weight);
      if (questionPhysiqueNotComplete) {
        toast('体格信息需要填写完整');
        return;
      }
      if (this.answers && _.isEmpty(this.answers)) {
        toast('体质问题需要答完');
        return;
      }
      const physiqueAllisCheck = this.height && this.weight;
      const physicalAllisCheck = !!this.answers;
      if (this.childInfo.id && (!physiqueAllisCheck && !physicalAllisCheck)) {
        toast('体质，体格至少评测一项');
        return;
      }
      if (physiqueAllisCheck) {
        physiqueParams = {
          height: this.height,
          weight: this.weight
        };
      }
      if (this.answers) {
        physicalParams = {
          answer: this.answers
        };
      }
      if (this.childRequest) {
        const childParams = {
          ...this.childInfo
        };
        this.upData(url.addMember, childParams)
          .then(res => {
            this.isNewBaby = true;
            if (physiqueParams) {
              physiqueParams.u_id = res.u_id;
              this.requestArray.push(this.upData(url.physique, physiqueParams));
            }
            if (this.answers) {
              physicalParams.u_id = res.u_id;
              this.requestArray.push(this.upData(url.physical, physicalParams));
            }
            if (this.requestArray.length) {
              this.promiseAll();
              this.childRequest = null;
              this.id = res.u_id;
              return;
            }
            this.childRequest = null;
            this.id = res.u_id;
            changeEditStatus(false);
            this.next(1);
          })
          .catch(catchAppError);
        return;
      }
      if (physiqueParams) {
        physiqueParams.u_id = this.childInfo.id;
        this.requestArray.push(this.upData(url.physique, physiqueParams));
      }
      if (this.answers) {
        physicalParams.u_id = this.childInfo.id;
        this.requestArray.push(this.upData(url.physical, physicalParams));
      }
      this.requestArray.length && this.promiseAll();
      this.id = this.childInfo.id;
    },
    promiseAll() {
      Promise.all(this.requestArray)
        .then(() => {
          changeEditStatus(false);
          this.next(1);
        })
        .catch(catchAppError);
    },
    upData(upUrl, params) {
      return http
        .post(upUrl, params)
        .then(res => res)
        .catch(catchAppError);
    },
    next() {
      this.activeTab = `${+this.activeTab + 1}`;
    },
    back(clearBabyInfo) {
      // clearData 区别在于是否保留宝宝信息。如果是新建宝宝就比较麻烦
      if (this.activeTab === '0') return;
      this.clearData();
      if (clearBabyInfo) {
        if (this.isNewBaby) {
          this.backBabyId = this.id;
          this.isnewBaby = false;
        }
        this.clearBabyInfo();
      }
      this.activeTab = `${this.activeTab - 1}`;
    }
  }
};
</script>

<style lang="scss" module="s">
@import '../assets/css/util.scss';

:global {
  .el-tabs__content {
    overflow: visible;
  }
  input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button {
    -webkit-appearance: none !important;
    margin: 0;
  }
  input[type='number'] {
    -moz-appearance: textfield;
  }
}
.evaluation {
  :global {
    .el-tabs__content {
      overflow: visible;
    }
    .el-tabs--card > .el-tabs__header .el-tabs__item {
      display: none;
    }
    .el-tabs__header.is-bottom {
      display: none;
    }
    .tab-step {
      width: 100%;
    }
    .btn-back {
      position: absolute;
      top: -65px;
      right: 30px;
    }
    .el-card {
      margin-bottom: 20px;
    }
    .baby {
      width: 100%;
      font-size: 16px;
      .w120 {
        width: 120px;
      }
      .el-card__body .one {
        &.with-tips {
          .tips {
            margin-left: -210px;
          }
        }
        display: flex;
        align-items: center;
        .child {
          margin-right: 20px;
          width: 300px;
          .item-text {
            color: #4b90ff;
          }
          .el-input__inner {
            border-color: #4b90ff;
            color: #4b90ff;
            padding-left: 15px;
            padding-right: 15px;
          }
          .item-icon {
            width: 12px;
            height: 12px;
            background-color: #4b90ff;
            display: inline-block;
            border-radius: 50%;
            margin-bottom: 3px;
            margin-right: 5px;
            vertical-align: middle;
          }
          .el-radio-button {
            margin-right: 10px;
            .el-radio-button__inner {
              border-left: 1px solid #4b90ff;
              border: 1px solid #4b90ff;
              color: #4b90ff;
              border-radius: 20px;
              padding: 7px 15px;
            }
            .el-radio-button__orig-radio:checked + .el-radio-button__inner {
              background-color: #ffb03e;
              border-left: 1px solid #ffb03e;
              border: 1px solid #ffb03e;
              box-shadow: -1px 0 0 0 #ffb03e;
              color: #fff;
            }
          }
        }
      }
      .float-right {
        vertical-align: middle;
      }
    }
    .submit {
      position: fixed;
      right: 40px;
      width: 142px;
      height: 57px;
      line-height: 57px;
      font-size: 16px;
      text-align: center;
      color: #fff;
      background-image: url('../assets/img/WechatIMG1225.png');
      background-position: center center;
      border: none;
      background-repeat: no-repeat;
      top: 275px;
      &:hover {
        cursor: pointer;
      }
    }
  }
}
</style>
